package com.mailanalyzer.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.channels.FileChannel;



public class FileUtil {

	public static String readFile(File file) {
		return readFile(file.getPath());
	}

	public static String readFile(String filePath) {
		StringBuffer buffer = new StringBuffer();
		BufferedReader br = null;
		try {
			FileInputStream fstream = new FileInputStream(filePath);
			DataInputStream in = new DataInputStream(fstream);
			br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			while ((strLine = br.readLine()) != null) {
				buffer.append(strLine + "\n");
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				if (br != null)
					br.close();
			} catch (Exception e) {
			}
		}
		return buffer.toString();

	}

	public static void writeFile(File file, String text) {
		try {
			if (!file.exists()) {
				if (!file.createNewFile())
					System.err.println("Can't create the file [" + file.getAbsolutePath() + "]");
			}
			BufferedWriter out = new BufferedWriter(new FileWriter(file));
			out.write(text);
			out.close();
			out = null;
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void copyFile(File in, File out) throws IOException {
		FileChannel inChannel = new FileInputStream(in).getChannel();
		FileChannel outChannel = new FileOutputStream(out).getChannel();
		try {
			inChannel.transferTo(0, inChannel.size(), outChannel);
		} catch (IOException e) {
			throw e;
		} finally {
			if (inChannel != null)
				inChannel.close();
			if (outChannel != null)
				outChannel.close();
		}
	}

}
